package com.wqr.mobile.android.ui.listview;

import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wqr.mobile.android.ui.BaseActivity;
import com.wqr.mobile.android.ui.R;
import com.wqr.mobile.android.ui.adapter.MBaseAdapter;
import com.wqr.mobile.android.ui.api.API;
import com.wqr.mobile.android.ui.bean.WeiboSearch;
import com.wqr.mobile.android.ui.bean.WeiboSearch.WeiboUser;
import com.wqr.mobile.android.ui.bean.WeiboUserHolder;
import com.wqr.mobile.android.ui.net.ImageDownloader;
import com.wqr.mobile.android.ui.net.NetworkManager;
import com.wqr.mobile.android.ui.task.HttpRequestTask;
import com.wqr.mobile.android.ui.task.HttpRequestTask.HttpTaskCallBack;
import com.wqr.mobile.android.ui.task.HttpTaskResult;

public class DoubleItemList extends BaseActivity implements API, Callback, HttpTaskCallBack, OnScrollListener {

	private static final int SCROLL_FINISHED = 0;
	private Context mContext;
	private MBaseAdapter<WeiboUser, WeiboUserHolder> mAdapter;

	private HttpRequestTask mImageTask;
	private NetworkManager mNetworkManager;
	private ImageDownloader mImagedownloader;
	private String next_page = "q=杨幂";
	private Handler mHandler;
	private View mLoadView;
	private GridView mGridView;
	private TextView mGridLoadItem;

	@Override
	public void onTaskStart() {
	}

	private void setTitle() {
		if (mAdapter != null) {
			setTitle("微博数-->" + mAdapter.getCount());
		}
	}

	@Override
	public HttpTaskResult onTaskRunning(Object... params) {
		String message = (String) params[0];
		if (mNetworkManager == null) {
			mNetworkManager = NetworkManager.getInstance();
		}
		return new HttpTaskResult(message, mNetworkManager.getRequest(mContext, next_page, WEIBO_SEARCH));
	}

	@Override
	public void onCancelled(Status status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskFinished(HttpTaskResult result) {
		if (result != null && result.getResult() != null) {
			Gson g = new Gson();
			WeiboSearch data = g.fromJson(result.getResult(), WeiboSearch.class);
			next_page = data.next_page.replace("?", "&");
			if (mAdapter == null) {
				createAdapter(data.results);
			} else {
				mAdapter.addList(data.results);
				mHandler.sendEmptyMessage(SCROLL_FINISHED);
			}
		}
	}

	private void createAdapter(List<WeiboUser> mUsers) {
		if (mImagedownloader == null) {
			mImagedownloader = new ImageDownloader(mContext);
		}
		mAdapter = new MBaseAdapter<WeiboUser, WeiboUserHolder>(mContext, R.layout.layout_weibo_search_item,
				new WeiboUserHolder(), mUsers) {

			@Override
			public void findHolderViews(View convertView, WeiboUserHolder holder) {
				holder.item_icon = (ImageView) convertView.findViewById(R.id.item_icon);
				holder.created_at = (TextView) convertView.findViewById(R.id.item_created_at);
				holder.item_text = (TextView) convertView.findViewById(R.id.item_text);
				holder.item_toUser = (TextView) convertView.findViewById(R.id.item_toUser);
				holder.item_user = (TextView) convertView.findViewById(R.id.item_user);
			}

			@Override
			public void setItemFromHolder(WeiboUserHolder holder, WeiboUser item) {
				mImagedownloader.download(item.profile_image_url, holder.item_icon);
				holder.created_at.setText(item.created_at);
				holder.item_text.setText(item.text);
				holder.item_toUser.setText(item.to_user);
				holder.item_user.setText(item.from_user);
			}

			@Override
			public void _onItemClick(Context context, AdapterView<?> parent, View view, int position, long id, WeiboUser item) {
				Toast.makeText(mContext, item.toString(), 1).show();
			}
		};
		mHandler.sendEmptyMessage(FINISHED);

	}

	@Override
	public boolean handleMessage(Message msg) {
		setTitle();
		switch (msg.what) {
		case START:
			mLoadView.setVisibility(VISIBLE);
			break;
		case SCROLL_FINISHED:
			mGridLoadItem.setVisibility(GONE);
			break;
		case FINISHED:
			mLoadView.setVisibility(GONE);
			mGridView.setAdapter(mAdapter);
			mAdapter.setOnItemClickListener(mGridView);
			mGridView.setOnScrollListener(this);
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	protected void destory() {
		if (mImageTask != null) {
			mImageTask = null;
		}
	}

	@Override
	protected void setUpViews() {
		setContentView(R.layout.activity_double_list);
		mLoadView = findViewById(R.id.layout_load);
		mGridView = (GridView) findViewById(R.id.gridView1);
		mGridView.setCacheColorHint(android.R.color.background_dark);
		mGridLoadItem = (TextView) findViewById(R.id.gridLoadItem);
	}

	@Override
	protected void setUpModels() {
		mContext = this;
		mHandler = new Handler(this);
		mHandler.sendEmptyMessage(START);
		mImageTask = new HttpRequestTask(this);
		mImageTask.execute(next_page);

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (mGridView == view) {
			if (firstVisibleItem + visibleItemCount == totalItemCount) {
				pushNewList();
			}
		}
	}

	/**
	 * 加载新的comment list页
	 */
	private synchronized void pushNewList() {
		Log.i(TAG, "onScroll---");
		if (mImageTask != null && !mImageTask.isCancelled() && mImageTask.getStatus() != AsyncTask.Status.FINISHED) {
			return;
		}
		mGridLoadItem.setVisibility(VISIBLE);
		mImageTask = new HttpRequestTask(this);
		mImageTask.execute(next_page);
	}

}
